import install from './install'
import createMatcher from './create-matcher';
import HashHistory from './history/hashHistory';
import BrowserHistory from './history/browserHistory';

class VueRouter{
  constructor(options) {
    let routesWrap = options.routes || []
    console.log(routesWrap)
    // 创建匹配器
    this.matcher = createMatcher(routesWrap)
    // 创建历史管理
    // 两种模式
    this.mode = options.mode || 'hash'
    switch(this.mode) {
      case 'hash':
        this.history = new HashHistory(this)
        break
      case 'history':
        this.history = new BrowserHistory(this)
        break
    }
    this.beforeHooks = []

  }
  match(location) {
    return this.matcher.match(location)
  }
  init(rootComp) {
    // 根据用户用户配置  做出一个映射表来

    // 根据路径 实现一下 页面链接的跳转
    const history = this.history
    // 跳转路径 进行匹配操作
    let setupHashListener = () => {
      history.setupListener()
    }

    history.transitionTo(history.getCurrentLocation(), setupHashListener)

    history.listen((route)=>{
      rootComp._route = route
    })
  }
  push(location) {
    const history = this.history
    window.location.hash = location
  }
  beforeEach(fn) {
    this.beforeHooks.push(fn)
  }
}

VueRouter.install = install

export default VueRouter